package com.zhentao.recharge.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.Result;
import com.zhentao.pojo.TOrder;
import com.zhentao.recharge.service.RechargeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值记录Controller
 * 
 * @author zhentao
 * @since 2024-08-13
 */
@Slf4j
@RestController
@RequestMapping("/recharge")
@CrossOrigin(origins = "*", maxAge = 3600)
public class RechargeController {

    @Autowired
    private RechargeService rechargeService;

    /**
     * 分页查询门诊充值记录
     * 
     * @param page 页码
     * @param pageSize 每页大小
     * @param patientId 患者ID
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param bizType 业务类型
     * @return 充值记录分页数据
     */
    @GetMapping("/list")
    public Result<IPage<TOrder>> getRechargeRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize,
            @RequestParam(required = false) Long patientId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) String bizType) {
        
        log.info("查询充值记录，页码：{}，每页大小：{}，患者ID：{}，开始日期：{}，结束日期：{}，业务类型：{}", 
                page, pageSize, patientId, startDate, endDate, bizType);
        
        try {
            Page<TOrder> pageParam = new Page<>(page, pageSize);
            IPage<TOrder> result = rechargeService.getRechargeRecords(pageParam, patientId, startDate, endDate, bizType);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询充值记录失败", e);
            return Result.error("查询充值记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据患者ID查询充值记录
     * 
     * @param patientId 患者ID
     * @return 充值记录列表
     */
    @GetMapping("/patient/{patientId}")
    public Result<List<TOrder>> getRechargeRecordsByPatientId(@PathVariable Long patientId) {
        log.info("根据患者ID查询充值记录，患者ID：{}", patientId);
        
        try {
            List<TOrder> result = rechargeService.getRechargeRecordsByPatientId(patientId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("根据患者ID查询充值记录失败", e);
            return Result.error("根据患者ID查询充值记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单ID查询充值记录详情
     * 
     * @param orderId 订单ID
     * @return 充值记录详情
     */
    @GetMapping("/detail/{orderId}")
    public Result<TOrder> getRechargeDetail(@PathVariable Integer orderId) {
        log.info("查询充值记录详情，订单ID：{}", orderId);
        
        try {
            TOrder result = rechargeService.getRechargeDetail(orderId);
            if (result != null) {
                return Result.success(result);
            } else {
                return Result.error("未找到该充值记录");
            }
        } catch (Exception e) {
            log.error("查询充值记录详情失败", e);
            return Result.error("查询充值记录详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增充值记录
     * 
     * @param order 充值记录
     * @return 操作结果
     */
    @PostMapping("/add")
    public Result<Boolean> addRechargeRecord(@RequestBody TOrder order) {
        log.info("新增充值记录，订单编号：{}", order.getOrderNumber());
        
        try {
            boolean result = rechargeService.addRechargeRecord(order);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("新增充值记录失败");
            }
        } catch (Exception e) {
            log.error("新增充值记录失败", e);
            return Result.error("新增充值记录失败：" + e.getMessage());
        }
    }

    /**
     * 更新充值记录
     * 
     * @param order 充值记录
     * @return 操作结果
     */
    @PutMapping("/update")
    public Result<Boolean> updateRechargeRecord(@RequestBody TOrder order) {
        log.info("更新充值记录，订单ID：{}", order.getOrderId());
        
        try {
            boolean result = rechargeService.updateRechargeRecord(order);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("更新充值记录失败");
            }
        } catch (Exception e) {
            log.error("更新充值记录失败", e);
            return Result.error("更新充值记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除充值记录
     * 
     * @param orderId 订单ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{orderId}")
    public Result<Boolean> deleteRechargeRecord(@PathVariable Integer orderId) {
        log.info("删除充值记录，订单ID：{}", orderId);
        
        try {
            boolean result = rechargeService.deleteRechargeRecord(orderId);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("删除充值记录失败");
            }
        } catch (Exception e) {
            log.error("删除充值记录失败", e);
            return Result.error("删除充值记录失败：" + e.getMessage());
        }
    }

    	/**
	 * 查询患者卡余额
	 * 
	 * @param patientId 患者ID
	 * @return 卡余额信息
	 */
	@GetMapping("/balance")
	public Result<Map<String, Object>> getCardBalance(@RequestParam(required = false) Long patientId) {
		log.info("查询患者卡余额，患者ID：{}", patientId);
		
		try {
			// 这里应该从数据库查询实际的余额
			// 暂时返回模拟数据
			Map<String, Object> balanceInfo = new HashMap<>();
			balanceInfo.put("balance", 150.50); // 模拟余额
			balanceInfo.put("cardNumber", "39000909000000");
			balanceInfo.put("lastUpdateTime", new Date());
			
			return Result.success(balanceInfo);
		} catch (Exception e) {
			log.error("查询卡余额失败", e);
			return Result.error("查询卡余额失败：" + e.getMessage());
		}
	}

	/**
	 * 健康检查接口
	 * 
	 * @return 服务状态
	 */
	@GetMapping("/health")
	public Result<String> health() {
		return Result.success("充值服务运行正常");
	}
} 